import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useAuthStore = defineStore('auth', () => {
  const token = ref<string | null>(loadToken())
  const userName = ref<string>('')
  const userAvatar = ref<string>('')

  const isLoggedIn = computed(() => !!token.value)

  function loadToken() {
    try {
      return localStorage.getItem('auth_token')
    } catch {
      return null
    }
  }

  function saveToken(val: string | null) {
    if (val) localStorage.setItem('auth_token', val)
    else localStorage.removeItem('auth_token')
  }

  function login(fakeToken: string, name?: string, avatar?: string) {
    token.value = fakeToken
    userName.value = name || '用户'
    userAvatar.value = avatar || ''
    saveToken(fakeToken)
  }

  function logout() {
    token.value = null
    userName.value = ''
    userAvatar.value = ''
    saveToken(null)
  }

  return { token, userName, userAvatar, isLoggedIn, login, logout }
})

